package com.yanq.liancar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.MailAddressAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.MailAddressBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/*
 *  @创建者     liyan
 *  @创建时间   2018/9/10  10:23
 *  @描述       {
 *
 *  1、小C（我的）：MineFragment
 *  2、小B（我的）：BMineFragment
 *
 */

public class MailAddressActivity extends BaseToolbarActivity {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private int page;
    private Boolean isClear = true;
    private MailAddressAdapter mailAddressAdapter;
    private List<MailAddressBean.DataBean> mailAddressBeanList = new ArrayList<>();
    private String token, where;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true, false);
        setContentView(R.layout.activity_mail_address);
        ButterKnife.bind(this);
        where = getIntent().getExtras().getString("where");
        if ("MineFragment".equals(where)) {
            token = UserBean.getcToken(this);
        } else {
            token = UserBean.getbToken(this);
        }
        mTvTitle.setText("邮寄地址");
        mIvRight.setVisibility(View.VISIBLE);
        mIvRight.setImageResource(R.mipmap.tianjia);

        mIvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("where", where);
                RxActivityTool.skipActivity(mContext, AddMailAddressActivity.class, bundle);
            }
        });

        //myDialog();
        initRecyclerview();
        initListener();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getAddressList();
    }

    private void initRecyclerview() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        mailAddressAdapter = new MailAddressAdapter(R.layout.item_mailaddress, mailAddressBeanList);
        recyclerview.setAdapter(mailAddressAdapter);

        mailAddressAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_delete:
                        deleteAddress(mailAddressBeanList.get(position).getId(), position);
                        break;
                    case R.id.img_modify:
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", mailAddressBeanList.get(position));
                        RxActivityTool.skipActivity(mContext, ModifyMailAddressActivity.class, bundle);
                        break;
                    case R.id.ll_default:
                        setDefault(mailAddressBeanList.get(position).getId(), position);
                        break;
                }
            }
        });
        mailAddressAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!"MineFragment".equals(where)&&!"BMineFragment".equals(where)) {
                    Intent intent = new Intent();
                    intent.putExtra("addressid", mailAddressBeanList.get(position).getId() + "");
                    intent.putExtra("name", mailAddressBeanList.get(position).getGainpeo());
                    intent.putExtra("phone", mailAddressBeanList.get(position).getCont_phone());
                    intent.putExtra("address", mailAddressBeanList.get(position).getGainaddress() + mailAddressBeanList.get(position).getAddr_detail());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isClear = true;


                refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                isClear = false;

                refreshLayout.finishLoadMore();
            }

        });
    }

    //获取地址列表
    private void getAddressList() {
        OkGo.<String>post(Config.s + "llc/api/findpostList")
                .tag(this)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        MailAddressBean addressBean = gson.fromJson(response.body(), MailAddressBean.class);
                        if (addressBean.isIsSuccess()) {
                            if (isClear) {
                                mailAddressBeanList.clear();
                            }
                            mailAddressBeanList.addAll(addressBean.getData());

                            Collections.sort(mailAddressBeanList, new Comparator<MailAddressBean.DataBean>() {
                                @Override
                                public int compare(MailAddressBean.DataBean o1, MailAddressBean.DataBean o2) {
                                    int i = o2.getDefault_mark() - o1.getDefault_mark();
                                    return i;
                                }
                            });
                            mailAddressAdapter.setNewData(mailAddressBeanList);
                        } else {
                            RxToast.error(addressBean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    //设置默认地址
    private void setDefault(int id, final int position) {
        LogUtils.e("position==", position + "");
        OkGo.<String>post(Config.s + "llc/api/updateDefaultMark")
                .tag(this)
                .params("token", token)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
                            //                            LogUtils.e("mailAddressBeanList==",mailAddressBeanList.size()+"");
                            //                            for (int i = 0; i < mailAddressBeanList.size(); i++) {
                            //                                if (position == i) {
                            //                                    mailAddressBeanList.get(position).setDefault_mark(1);
                            //                                    LogUtils.e("aaaa",mailAddressBeanList.get(position).getDefault_mark()+"");
                            //                                } else {
                            //                                    mailAddressBeanList.get(position).setDefault_mark(0);
                            //                                    LogUtils.e("bbbb==",mailAddressBeanList.get(position).getDefault_mark()+"");
                            //                                }
                            //                            }
                            //                            LogUtils.e("mailAddressBeanList==",mailAddressBeanList.get(position).getDefault_mark()+"");
                            //                            Collections.sort(mailAddressBeanList, new Comparator<MailAddressBean.DataBean>() {
                            //                                @Override
                            //                                public int compare(MailAddressBean.DataBean o1, MailAddressBean.DataBean o2) {
                            //                                    int i = o2.getDefault_mark() - o1.getDefault_mark();
                            //                                    return i;
                            //                                }
                            //                            });
                            //                            mailAddressAdapter.setNewData(mailAddressBeanList);
                            getAddressList();
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    //删除地址
    private void deleteAddress(int id, final int position) {
        OkGo.<String>post(Config.s + "llc/api/deleteSendPost")
                .tag(this)
                .params("token", token)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
                            mailAddressBeanList.remove(position);
                            mailAddressAdapter.setNewData(mailAddressBeanList);
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    //    private void myDialog(){
    //        final Dialog bottomDialog = new Dialog(this);
    //        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_subm, null);
    //        bottomDialog.setContentView(contentView);
    //        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
    //        params.width = getResources().getDisplayMetrics().widthPixels -100;
    //        contentView.setLayoutParams(params);
    //        bottomDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
    //        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
    //        bottomDialog.setCanceledOnTouchOutside(false);
    //        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    //        bottomDialog.show();
    //
    //        TextView tv_cancle = bottomDialog.findViewById(R.id.tv_dialog_back);
    //        tv_cancle.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View view) {
    //
    //                bottomDialog.dismiss();
    //            }
    //        });
    //
    //    }

}
